using System;
using System.IO;
using Petra.Gis.Geometry;
using Petra.Gis.Geometry.Support;

namespace Petra.Gis.DataServices.SHP
{
	/// <summary>
	/// Converts a Shapefile point to a OGIS Point.
	/// </summary>
  public partial class GeometryFactory : IGeometryFactory
	{
		
		/// <summary>
		/// Reads a stream and converts the shapefile record to an equilivent geometry object.
		/// </summary>
		/// <param name="file">The stream to read.</param>
		/// <param name="geometryFactory">The geometry factory to use when making the object.</param>
		/// <returns>The Geometry object that represents the shape file record.</returns>
    public static GeometryBase binaryToPoint(byte[] data)
		{

      BinaryReader br = new BinaryReader(new MemoryStream(data));
      //int shapeTypeNum = br.ReadInt32();

      ShapeGeometryTypes shapeType = (ShapeGeometryTypes)br.ReadInt32();
      if ( ! ( shapeType == ShapeGeometryTypes.Point  || shapeType != ShapeGeometryTypes.PointM   ||
               shapeType != ShapeGeometryTypes.PointZ ))	
				throw new ApplicationException("Attempting to load a point as point.");

      return new Point(br.ReadDouble(), br.ReadDouble(), 0);
		}
		




		/// <summary>
		/// Writes to the given stream the equilivent shape file record given a Geometry object.
		/// </summary>
		/// <param name="geometry">The geometry object to write.</param>
		/// <param name="file">The stream to write to.</param>
		/// <param name="geometryFactory">The geometry factory to use.</param>
    public static byte[] pointToBinary(GeometryBase geometry)
		{

      Point geom = (Point)geometry;

      byte[] result = new byte[10];
      BinaryWriter b = new BinaryWriter(new MemoryStream(result));

      b.Write((Int16)ShapeGeometryTypes.Point);
      b.Write(geom.X);
      b.Write(geom.Y);

      b.Close();

      return result;
		}

    ///// <summary>
    ///// Gets the length in bytes the Geometry will need when written as a shape file record.
    ///// </summary>
    ///// <param name="geometry">The Geometry object to use.</param>
    ///// <returns>The length in bytes the Geometry will use when represented as a shape file record.</returns>
    //public override int GetLength(Geometry geometry)
    //{
    //  return 10; // The length of two doubles in 16bit words + the shapeType
    //}		
	}
}
